import axios from "axios";
import path from "path";
import dotenv from "dotenv";

dotenv.config();

const GITEE_TOKEN = process.env.GITEE_TOKEN!;
const GITEE_OWNER = process.env.GITEE_OWNER!;
const GITEE_REPO = process.env.GITEE_REPO!;
const GITEE_BRANCH = process.env.GITEE_BRANCH || "main";

export const uploadImageToGitee = async (file: Express.Multer.File) => {
  try {
    // 检查环境变量是否设置
    if (!GITEE_TOKEN || !GITEE_OWNER || !GITEE_REPO) {
      console.error("缺少必要的 Gitee 配置环境变量");
      throw new Error("Gitee 配置不完整，请检查环境变量");
    }
    
    const ext = path.extname(file.originalname);
    const newName = `${Date.now()}-${Math.floor(Math.random() * 10000)}${ext}`;
    const giteePath = `images/${newName}`;
    const content = file.buffer.toString("base64");
    const apiUrl = `https://gitee.com/api/v5/repos/${GITEE_OWNER}/${GITEE_REPO}/contents/${giteePath}`;
    
    console.log(`准备上传图片到 Gitee: ${giteePath}`);
    
    const resp = await axios.post(apiUrl, {
      access_token: GITEE_TOKEN,
      content,
      message: `upload image ${newName}`,
      branch: GITEE_BRANCH,
    });
    
    console.log(`图片上传成功: ${giteePath}`);
    return `https://gitee.com/${GITEE_OWNER}/${GITEE_REPO}/raw/${GITEE_BRANCH}/${giteePath}`;
  } catch (error: any) {
    console.error("上传图片到 Gitee 失败:", error.message);
    if (error.response) {
      console.error("Gitee API 响应:", error.response.data);
    }
    throw error;
  }
};

export const uploadImagesToGitee = async (files: Express.Multer.File[]) => {
  const results = await Promise.all(
    files.map((file) => uploadImageToGitee(file))
  );
  return results;
};